package com.codegeek.project.mybatisTypeHandler;

import com.alibaba.fastjson.JSONArray;
import com.codegeek.project.mybatisTypeHandler.struct.CGSensorTypeItem;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wj
 * @ClassName
 * @Description
 * @date 2020-02-20
 */
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes(List.class)
public class SensorTypeItemTypeHandler extends BaseTypeHandler<List<CGSensorTypeItem>> {

    public static final Logger logger = LogManager.getLogger("FileUtils");

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<CGSensorTypeItem> cgSensorTypeItems, JdbcType jdbcType) throws SQLException {
        try {
            JSONArray itemArray = new JSONArray((List) cgSensorTypeItems);
            String items = itemArray.toString();
            preparedStatement.setString(i, items);
        }
        catch (Exception e){
            preparedStatement.setString(i,null);
            e.printStackTrace();
            logger.error(e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<CGSensorTypeItem> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        try{
            String items=resultSet.getString(s);
            List<CGSensorTypeItem> itemArray=JSONArray.parseArray(items,CGSensorTypeItem.class);
            return itemArray;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e);
            return null;
        }

    }

    @Override
    public List<CGSensorTypeItem> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        try {
            String items = resultSet.getString(i);
            List<CGSensorTypeItem> itemArray = JSONArray.parseArray(items, CGSensorTypeItem.class);
            return itemArray;
        }
        catch (Exception e){
            e.printStackTrace();
            logger.error(e);
            return null;
        }
    }

    @Override
    public List<CGSensorTypeItem> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        try {
            String items = callableStatement.getString(i);
            List<CGSensorTypeItem> itemArray = JSONArray.parseArray(items, CGSensorTypeItem.class);
            return itemArray;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e);
            return null;
        }
    }
}
